<template>
  <div id="specCollection">
    <!-- <Breadcrumb content="标本接收" /> -->
    <div class="bodyContent">
      <el-tabs v-model="activeName" type="border-card" @change="tabSelectChange">
        <el-tab-pane :label="paneNameByCode" name="speccollection">
          <vxe-toolbar perfect>
            <template #buttons>
              <span class="margin-lr-xs text-Bold text-shadow">条码号:</span>
              <vxe-input ref="specCodeInput" v-model="form.specCode" clearable @compositionstart.native="compositionstart"
                @compositionend.native="compositionend" @keyup="specInputKeyUp" :disabled="isspdisable"></vxe-input>
              <!-- <vxe-button type="text" content="标本接收" class="button-blue" :disabled="newSpecSignDetailList.length === 0"
                @click="handleSign"></vxe-button> -->
              <!-- <vxe-button type="text" content="清屏" class="button-blue" @click="ClearScreen"></vxe-button> -->
              <vxe-button icon="vxe-icon-undo" type="text" class-name="text-black text-bold" content="标本退回"
                class="button-red" @click="returnSpec" v-if="isBbth"></vxe-button>
              <vxe-button type="text" content="生成交接单" class="button-blue" @click="generateReceipt"
                v-if="isCreatReceipt"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印交接单" :loading="showLoading"
                @click="quietPrint" v-if="isPrint"></vxe-button>
            </template>
            <template #tools>
              <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">{{ paneNameByCode }}</span>
            </template>
          </vxe-toolbar>
          <div class="padding-xs" style="background-color: #f8f8f9">
            <div style="border: 1px dashed green; width: 100%" class="radius line-olive flex justify-start bg-gray">
              <div style="width: 70px; padding: 2.5px" class="flex justify-center text-center">
                <div style="width: 65px; height: 100%" class="radius solid bg-yellow"></div>
              </div>
              <div style="height: 100%" class="bg-gray">
                <vxe-form :data="currentSpecSignDetail" class-name="padding-xs width-100-percentage"
                  style="background-color: rgba(0, 0, 0, 0)" title-width="70px">
                  <vxe-form-gather span="6">
                    <vxe-form-item title="条码号" field="reqNo" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">条码号</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.reqNo" readonly placeholder="条码号" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="6">
                    <vxe-form-item title="申请号" field="remark1" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">申请号</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.remark1" readonly placeholder="申请号" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="6">
                    <vxe-form-item title="病人ID号" field="patId" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">病人ID号</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.patId" readonly placeholder="病人ID号" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="6">
                    <vxe-form-item title="姓名" field="patNa" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">姓名</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.patNa" readonly placeholder="姓名" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="6">
                    <vxe-form-item title="性别" field="sexNa" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">性别</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.sexNa" readonly placeholder="性别" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="6">
                    <vxe-form-item title="当前状态" field="isSign" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">当前状态</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.stateNa" readonly placeholder="当前状态" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                  <vxe-form-gather span="12">
                    <vxe-form-item title="申请项目" field="feeName" class-name="width-100-percentage">
                      <template #title>
                        <span class="text-bold padding-left-xs">申请项目</span>
                      </template>
                      <template #default="{ data }">
                        <vxe-input v-model="data.feeName" readonly placeholder="申请项目" class-name="width-100-percentage" />
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                </vxe-form>
              </div>
            </div>
          </div>
          <div class="specSignDetailTable" :style="{ height: 'calc(100% - 40px - 82px - 5px)' }">
            <vxe-table ref="specSignDetailTable" v-loading="loading" border class="mytable-scrollbar" height="auto"
              :menu-config="tableMenuTop" @menu-click="contextMenuClickEventTop" :data="specSignDetailList"
              :row-config="{ isCurrent: true, isHover: true }"
              :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" @current-change="specSignDetailRowClick"
              resizable show-overflow :tooltip-config="tooltipConfig">
              <!-- <vxe-column type="checkbox" width="26"></vxe-column> -->
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="isSuccess" title="状态" width="60" align="center">
                <template #default="{ row, rowIndex }">
                  <span v-if="row.loading" class="text-blue">接收中...</span>
                  <span v-else-if="row.isSuccess" class="text-18 text-green el-icon-success">
                    <el-icon color="#409EFC" class="no-inherit">
                      <CircleCheck />
                    </el-icon>
                  </span>
                  <span v-else class="text-blue" @click="againSign(row, rowIndex)">重新接收</span>
                </template>
              </vxe-column>
              <vxe-column field="reqNo" title="条码号" width="100px">
                <template #default="{ row }">
                  <span>{{ row.reqNo ? row.reqNo : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="remark1" title="申请号" width="120px">
                <template #default="{ row }">
                  <span>{{ row.remark1 ? row.remark1 : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="isSampling" title="状态" width="60px" align="center" v-if="code === 40 || code === '40'">
                <template #default="{ row }">
                  <span :class="row.isSampling === 1 ? 'text-blue' : 'text-red'">
                    {{ row.isSampling === 1 ? '已采样' : '未已采样' }}
                  </span>
                </template>
              </vxe-column>
              <!-- <vxe-column field="isSign" title="状态" width="80px" align="center" v-if="code===50||code==='50'">
                <template #default="{ row }">
                  <span :class="row.isSign ? 'text-blue' : 'text-red'">
                    {{ row.isSign === 1 ? '已送出' : '未送出' }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column field="isSign" title="状态" width="80px" align="center" v-if="code===70||code==='70'">
                <template #default="{ row }">
                  <span :class="row.isSign ? 'text-blue' : 'text-red'">
                    {{ row.isSign === 1 ? '已送达' : '未送达' }}
                  </span>
                </template>
              </vxe-column> -->
              <vxe-column field="isSign" title="状态" width="60px" align="center" v-if="code === 70 || code === '70'">
                <template #default="{ row }">
                  <span :class="row.isSign ? 'text-blue' : 'text-red'">
                    {{ row.isSign === 1 ? '已签收' : '未签收' }}
                  </span>
                </template>
              </vxe-column>
              <!-- <vxe-column field="isOriginal" title="是否原始标本" width="100px" align="center">
              <template #default="{ row }">
                <span v-if="row.spec" :class="row.spec.isOriginal ? 'text-blue' : 'text-red'">
                  {{ row.spec.isOriginal ? '是' : '否' }}
                </span>
              </template>
            </vxe-column> -->
              <!-- <vxe-column field="name" title="传送方式" width="100px"></vxe-column> -->
              <vxe-column field="patId" title="病人ID" width="100">
                <template #default="{ row }">
                  <span>{{ row.patId ? row.patId : '' }}</span>
                  <span></span>
                </template>
              </vxe-column>
              <vxe-column field="patNa" title="姓名" width="60">
                <template #default="{ row }">
                  <span>{{ row.patNa ? row.patNa : '' }}</span>
                  <span></span>
                </template>
              </vxe-column>
              <vxe-column field="sexNa" title="性别" width="45">
                <template #default="{ row }">
                  <span> {{ row.sexNa }}</span>
                  <span></span>
                </template>
              </vxe-column>
              <vxe-column field="medicalRecAge" title="年龄" width="50">
                <template #default="{ row }">
                  <span>{{ row.ageStr ? row.ageStr : '' }}</span>
                  <span></span>
                </template>
              </vxe-column>
              <vxe-column field="sampleTypeNa" title="样本类型" width="70">
                <template #default="{ row }">
                  <span>{{ row.sampleTypeNa ? row.sampleTypeNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="reqPurpose" title="申请项目" min-width="200">
                <template #default="{ row }">
                  <span>{{ row.reqPurpose ? row.reqPurpose : '' }}</span>
                  <span></span>
                </template>
              </vxe-column>
              <vxe-column field="reqDoctorNa" title="申请人" width="60">
                <template #default="{ row }">
                  <span>{{ row.reqDoctorNa ? row.reqDoctorNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="reqTime" title="申请时间" width="120">
                <template #default="{ row }">
                  <span>{{ row.reqTime ? row.reqTime : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="samplingDoctorNa" title="采集人" width="80" v-if="code === '40'">
                <template #default="{ row }">
                  <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="samplingTime" title="采集时间" min-width="120" v-if="code === '40'">
                <template #default="{ row }">
                  <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signer" title="签收人" width="80" v-if="code === '70'">
                <template #default="{ row }">
                  <span>{{ row.signerNa ? row.signerNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signTime" title="签收时间" width="120" v-if="code === '70'">
                <template #default="{ row }">
                  <span>{{ row.signTime ? row.signTime : '' }}</span>
                </template>
              </vxe-column>
              <!-- <vxe-column field="signer" title="接收人" width="80" v-if="code === 'bbjs'">
                <template #default="{ row }">
                  <span>{{ row.signerNa ? row.signerNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signTime" title="接收时间" width="120" v-if="code === 'bbjs'">
                <template #default="{ row }">
                  <span>{{ row.signTime ? row.signTime : '' }}</span>
                </template>
              </vxe-column> -->
              <vxe-column field="signer" title="送达人" width="80" v-if="code === '60'">
                <template #default="{ row }">
                  <span>{{ row.signerNa ? row.signerNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signTime" title="送达时间" width="120" v-if="code === '60'">
                <template #default="{ row }">
                  <span>{{ row.signTime ? row.signTime : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signer" title="送出人" width="80" v-if="code === '50'">
                <template #default="{ row }">
                  <span>{{ row.signerNa ? row.signerNa : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="signTime" title="送出时间" width="120" v-if="code === '50'">
                <template #default="{ row }">
                  <span>{{ row.signTime ? row.signTime : '' }}</span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </el-tab-pane>

        <el-dialog v-model="showDialog" :title="title" width="500px" @close="closeDialog">
          <!-- 修改表单 -->
          <vxe-form ref="detailForm" :data="receiptForm" :title-width="80" title-colon title-align="right"
            class-name="criticalValueResultForm margin-top-sm">
            <vxe-form-item title="交接人" span="10" field="handoverPersonName" :item-render="{}">
              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/hisEmployee/getEmployeePageList'" :displayField="[
                { title: '编号', props: 'code' }, //列标题
                { title: '名称', props: 'name' }
              ]" :searchParam="{}" :inputKeyName="'seachValue'" :isPage="true" :title="'点击选择员工'"
                @selectDataRow="SelecthandoverPersonIdClick" @clearValue="clearValuePersonId"
                @sliceValue="sliceHandlerPersonId" v-model="receiptForm.handoverPersonName" :inputWidth="'100%'" />
            </vxe-form-item>
            <vxe-form-item title="接收人" span="10" field="receiverName" :item-render="{}">
              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/hisEmployee/getEmployeePageList'" :displayField="[
                { title: '编号', props: 'code' }, //列标题
                { title: '名称', props: 'name' }
              ]" :searchParam="{}" :inputKeyName="'seachValue'" :isPage="true" :title="'点击选择员工'"
                @selectDataRow="SelectRowClickReceiver" @clearValue="clearValueHandlerReceiver"
                @sliceValue="sliceHandlerReceiver" v-model="receiptForm.receiverName" :inputWidth="'100%'" />
            </vxe-form-item>
            <vxe-form-item title="交接数量" span="10" field="quantity" :item-render="{}">
              <vxe-input v-model="receiptForm.quantity" readonly clearable></vxe-input>
            </vxe-form-item>

            <vxe-form-item span="24" align="center" :item-render="{}" class-name=" margin-top-sm">
              <template #default>
                <vxe-button status="primary" content="确定" @click="saveHandler('receiptForm')"></vxe-button>
                <vxe-button content="取消" @click="closeDialog('receiptForm')"></vxe-button>
              </template>
            </vxe-form-item>
          </vxe-form>
        </el-dialog>
        <el-tab-pane :label="paneHistoryNameByCode" name="speccollectionhistory">
          <LabSampleProcessByCodeHistory ref="refCodeAndAttributeData" />
        </el-tab-pane>

        <el-tab-pane :label="paneReceiptNameByCode" name="speccollectionhistoryReceipt" v-if="isCreatReceipt">
          <LabSampleProcessByCodeReceipt ref="refCodeAndAttributeReceiptData" />
        </el-tab-pane>

        <el-tab-pane label="标本查询" name="reqMainQuery">
          <LabReqMainQuery ref="refReqMainQuery" />
        </el-tab-pane>
      </el-tabs>
      <vxe-modal v-model="returnReasonModule" width="600" show-footer destroy-on-close>
        <template #title>
          <span style="color: red">标本退回理由</span>
        </template>
        <template #default>
          <div>
            <!-- <vxe-textarea
              v-model="returnReason"
              placeholder="请输入回退理由"
              :style="{ height: 'calc(40vh - 20px) !important' }"
              resize="vertical"
              className="vxe-textarea-height"
            ></vxe-textarea> -->
            <UnqualifiedSpecRec ref="unqualifiedSpecRecRef" @chackedReasonChange="chackedReasonChange" />
          </div>
        </template>
        <template #footer>
          <div class="flex justify-end padding-right-xs">
            <vxe-button class-name="margin-left-sm" content="取消" @click="returnReasonModule = false"></vxe-button>
            <vxe-button class-name="margin-left-sm" status="primary" content="确定" @click="confirmReturnSpec"></vxe-button>
          </div>
        </template>
      </vxe-modal>
    </div>
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { onMounted, ref, reactive, getCurrentInstance } from 'vue';
import { VXETable } from 'vxe-table';
import { AppStore } from '../../../stores/store';
import { IsEmpty, formatDateTime } from '@/utils/common';
import LabSampleProcessByCodeHistory from './LabSampleProcessByCodeHistory.vue';
import LabReqMainQuery from './LabReqMainQuery.vue';
import XEClipboard from 'xe-clipboard';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import UnqualifiedSpecRec from '@/components/UnqualifiedSpecRec.vue';
import LabSampleProcessByCodeReceipt from './LabSampleProcessByCodeReceipt.vue';
import SelectDataList from '@/components/SelectDataList.vue';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import { popTips } from '@/utils/TatTip';
import QuietPrint from '@/components/QuietPrint.vue';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let props = defineProps({}) as any;
let isspdisable = ref(false);
let tableMenuTop = {
  className: 'my-menus',
  body: {
    options: [
      [
        {
          code: 'copy',
          name: '复制内容',
          prefixIcon: 'vxe-icon-copy',
          className: 'my-copy-item',
          isVisible: false
        }
      ]
    ]
  },
  visibleMethod: ({ options, column }) => {
    const isVisible = column && column.field === 'specCode';
    options.forEach((list) => {
      list.forEach((item) => {
        if (column) {
          if (item.code === 'copy') {
            item.visible = isVisible;
          }
        } else {
          item.visible = false;
        }
      });
    });
    return true;
  }
};
let errData = {};
let store = AppStore();
let userInfo = store.userInfo;
let activeName = 'speccollection';
let showHistory = false;
let pageIndex = 1;
let totalCount = 0;
let loading = ref(false);
let lock = false;
let specSignDetailList = reactive([]); //列表
let newSpecSignDetailList = reactive([]); //未签收标本数组
let currentSpec = {} as any; //当前标本
let currentSpecSign = {} as any; //当前接收记录
let currentSpecSignDetail = reactive({
  reqNo: '',
  remark1: '',
  patId: '',
  patNa: '',
  sex: '',
  isSign: '',
  feeName: '',
  id: null
}); //当前采集记录详情
let currentRowIndex = 0;
let form = reactive({
  specCode: '',
  realSpecCode: '',
  searchValue: ''
});
let receiptForm = reactive({
  handoverPersonId: '',
  receiver: '',
  quantity: 0,
  batchNo: '',
  type: '',
  labReqMains: specSignDetailList,
  receiverName: '',
  handoverPersonName: ''
});

let refCodeAndAttributeData: any = ref(null); //把节点与属性数据传到历史信息查询子组件
let refReqMainQuery: any = ref(null);
let refCodeAndAttributeReceiptData: any = ref(null);
let isCreatReceipt = ref(true); //是否有生成交接单功能
let unqualifiedDetailIds = reactive({});

let printParamsObj = ref(null); //打印参数


function chackedReasonChange(val: any) {
  unqualifiedDetailIds = val;
  // console.log('---------unqualifiedDetailIds-------:', unqualifiedDetailIds.value);
}

const formData = reactive({})
const tooltipConfig = reactive<VxeTablePropTypes.TooltipConfig>({
  showAll: true,
  enterable: true,
  contentMethod: ({ type, column, row, items, _columnIndex }) => {
    const { field } = column;
    // 重写默认的提示内容
    if (field === 'reqPurpose') {
      return formData[row.feeCode.split(',')[0]];
    }
  }
});

// 方法定义区 =============
onMounted(() => {
  (proxy.$refs.specCodeInput as any).focus();
  code.value = proxy.$route.query.code;
  getProcessAttributeListByCode();
});
let code = ref('');
let processAttributeList = reactive([]); //流程节点属性
let paneNameByCode = ref('');
let paneHistoryNameByCode = ref('');
let paneReceiptNameByCode = ref('');
let isBbth = ref(false);
let showDialog = ref(false);
let title = ref('');
let type = '';
let isPrint = ref(false);
let showLoading = ref(false);

function quietPrint() {
  const $xTable = proxy.$refs.specSignDetailTable as any;
  let reqNos: any = [];
  $xTable.getTableData().tableData.forEach((item: any) => {
    reqNos.push(item.reqNo);
  });
  let reportId: any;
  if (reqNos.length > 0) {
    let url = `/api/pubReport/getReportByBusFormCode?code=signatureForm`;
    proxy.$http
      .get(url)
      .then((res: any) => {
        if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
          reportId = res.data.id;

          let ids = reqNos.join(',');
          printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'ids', Value: ids }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
        } else {
          proxy.$alert('查无报告模板', '提示');
        }
      })
      .catch((err: any) => {
        proxy.$alert('查询报告模板失败' + err, '提示');
        //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
  }
  //showLoading.value = true;
}

// 点击组件表格行
function SelecthandoverPersonIdClick(row) {
  receiptForm.handoverPersonId = row.code;
  receiptForm.handoverPersonName = row.name;
}
function clearValuePersonId() {
  receiptForm.handoverPersonId = '';
}
// 键盘事件删除输入框文字
function sliceHandlerPersonId() {
  let newStr = receiptForm.handoverPersonId.slice(0, -1);
  receiptForm.handoverPersonId = newStr;
}

// 点击组件表格行
function SelectRowClickReceiver(row) {
  receiptForm.receiver = row.code;
  receiptForm.receiverName = row.name;
}
function clearValueHandlerReceiver() {
  receiptForm.receiver = '';
}
// 键盘事件删除输入框文字
function sliceHandlerReceiver() {
  let newStr = receiptForm.receiver.slice(0, -1);
  receiptForm.receiver = newStr;
}

//批量生成交接单
function generateReceipt() {
  clearFormAndobj();
  if (specSignDetailList.length === 0) {
    VxeMessage('暂无数据，无法生成交接单', VxeNotifyType.error);
    return;
  }
  showDialog.value = true;
  receiptForm.quantity = specSignDetailList.length;
  receiptForm.type = type;
  receiptForm.batchNo = batchNo;
}

function closeDialog() {
  clearFormAndobj();
}
function clearFormAndobj() {
  for (const key of Object.keys(receiptForm)) {
    if (key === 'quantity') {
      receiptForm[key] = 0;
      break;
    }
    if (key === 'labReqMains') {
      break;
    }
    receiptForm[key] = '';
  }
  showDialog.value = false;
}

// 弹框保存
function saveHandler() {
  let $form = proxy.$refs.receiptForm;
  const url = '/lab/delivery/receipt/creatReceipt';
  let LabDeliveryReceipt = receiptForm;
  proxy.$http
    .post(url, LabDeliveryReceipt)
    .then((res) => {
      clearFormAndobj();
      if (res.status.code === 200) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        return;
      }
    })
    .catch((err) => {
      VxeMessage('交接单生成异常', VxeNotifyType.error);
    });
}
//根据code获取节点下的属性；
function getProcessAttributeListByCode() {
  processAttributeList.length = 0;
  if (IsEmpty(code.value)) {
    VxeMessage('无法确认跳转的当前界面，请检查标本流程配置中的编码值', VxeNotifyType.error);
    return;
  }
  let creatTitle = '生成';
  if (code.value === '70') {
    paneNameByCode.value = '标本签收';
    paneHistoryNameByCode.value = '标本历史签收';
    paneReceiptNameByCode.value = '历史签收交接单';
    type = '1';
  } else if (code.value === '40') {
    paneNameByCode.value = '标本采集';
    paneHistoryNameByCode.value = '标本历史采集';
    paneReceiptNameByCode.value = '历史采集交接单';
    type = '0';
  } else if (code.value === '50') {
    paneNameByCode.value = '标本送出';
    paneHistoryNameByCode.value = '标本历史送出';
    paneReceiptNameByCode.value = '历史送出交接单';
    type = '2';
  } else if (code.value === '60') {
    paneNameByCode.value = '标本送达';
    paneHistoryNameByCode.value = '标本历史送达';
    paneReceiptNameByCode.value = '历史送达交接单';
    type = '3';
  }
  title.value = paneReceiptNameByCode.value + creatTitle;
  const url = '/lab/process/set/getNodeListByCode';
  let isCreatReceiptValue = '0';
  proxy.$http
    .get(url, { params: { code: code.value } })
    .then(async (res: any) => {
      if (res.status.code === 200) {
        processAttributeList.push(...res.data);
        // if (processAttributeList.some((item) => item.processAttCode === 'bbth')) {
        //   isBbth.value = true;
        // }
        const refData = { refAttributeList: processAttributeList, code: code, type: type };
        if (!IsEmpty(processAttributeList)) {
          processAttributeList.forEach((item) => {
            //是否启用回退按钮
            if (item.isRollback) {
              isBbth.value = true;
            }
            //是否生成交接单
            if (item.isCreatReceipt) {
              isCreatReceipt.value = true;
              refCodeAndAttributeReceiptData.value.initPageReceipt(refData); //传递给右侧基本信息表单
              isCreatReceiptValue = '1';
            }
            //是否打印交接单
            if (item.isPrintReceipt) {
              isPrint.value = true;
            }
          });
          if (isCreatReceiptValue === '0') {
            isCreatReceipt.value = false;
          }
        }
        refCodeAndAttributeData.value.initPage(refData); //传递给右侧基本信息表单
        refReqMainQuery.value.initPage(refData);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 清空 currentSpecsamplingDetail 对象的所有属性
function clearCurrentSpecsamplingDetail() {
  Object.keys(currentSpecSignDetail).forEach((key) => {
    currentSpecSignDetail[key] = '';
  });
}
// 条码号输入框清空，并获取焦点
function clearSpecCodeInput() {
  isspdisable.value = false;
  form.specCode = '';
  setTimeout(() => {
    (proxy.$refs.specCodeInput as any).focus();
  }, 20);
}
// 条码号输入框失去焦点
function specCodeInputBlur() {
  (proxy.$refs.specCodeInput as any).blur();
}
// 条码号输入框中文输入法开始输入
function compositionstart() {
  console.log('compositionstart---');

  lock = true;
  form.realSpecCode = form.specCode;
}
// 条码号输入框中文输入法结束输入
function compositionend() {
  console.log('compositionend---');

  lock = false;
  form.specCode = form.realSpecCode;
}
// 键盘输入为中文状态，转为英文字符
function specInputKeyUp(e) {
  if (e.$event.code === 'Enter' || e.$event.code === 'NumpadEnter') {
    getspecByCode(form.specCode);
    selectAll();
  }
  if (!lock) {
    return;
  }
  if (e.key === 'Backspace' && form.realSpecCode) {
    form.realSpecCode = form.realSpecCode.slice(0, -1);
  }
  const reg = /^[\w!@#$%^&*\(\)-+=|':./<>?`~]{1}$/;
  if (reg.test(e.key)) {
    form.realSpecCode += e.key;
  }
  // form.specCode = form.realSpecCode;
}
let batchNo = '';
// 查询出标本数据后，进行接收操作
function specCodeInputEnter(specId, reqNo, index) {
  const url = '/lab/reqMain/createCollectionDetail';
  const data = {
    reqNo: reqNo,
    id: specId,
    batchNo: batchNo,
    actStateCode: code.value
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 1) {
        batchNo = res.status.msg;
        res.data[0].isSuccess = true;
        res.data[0].loading = false;
        Object.assign(currentSpecSignDetail, res.data[0]);
        Object.assign(specSignDetailList[index], res.data[0]);
      } else {
        currentSpec = {};
        clearCurrentSpecsamplingDetail();
        specSignDetailList.splice(index, 1);
        VxeMessage('异常', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      specCodeInputBlur();
      currentSpec = {};
      clearCurrentSpecsamplingDetail();
      specSignDetailList.splice(index, 1);
      proxy.$alert(err.data.error.message, '提示', {
        callback: (action) => {
          const time = setTimeout(() => {
            clearSpecCodeInput();
            clearTimeout(time);
          }, 200);
        }
      });
    });
  clearSpecCodeInput();
}

//新增性状
function handleAdd(specCode) {
  const newRow = {
    id: null,
    reqNo: null,
    specCode,
    loading: true, //是否正在创建
    isSuccess: false //是否创建成功
  };

  //specSignDetailList.push(newRow);
  specSignDetailList.unshift(newRow);
  //newSpecSignDetailList.push(newRow);
  newSpecSignDetailList.unshift(newRow);
  const $table = proxy.$refs.specSignDetailTable as any;
  $table.reloadData(specSignDetailList);
  $table.setEditRow(newRow);
  $table.setCurrentRow(newRow);
  return 0; //specSignDetailList.length - 1;
}
// 行点击事件
function specSignDetailRowClick({ row, rowIndex }) {
  currentRow = row;
  clearCurrentSpecsamplingDetail();
  currentRowIndex = rowIndex;
  Object.assign(currentSpecSignDetail, row);
}
// #region
// 获取标本信息
async function getspecByCode(specCode) {
  if (IsEmpty(specCode) || IsEmpty(specCode.trim())) {
    VxeMessage('条码号不可为空', VxeNotifyType.error);
    return;
  }
  isspdisable.value = true;
  //await popTips(`【TAT监控】标本签收到审核报告,大于TAT规定的最大时间:[10.0]分钟`);
  //console.log('-------->>>');
  try {
    const url = '/lab/reqMain/getReqMainByReqNo';
    proxy.$http
      .get(url, { params: { reqNo: specCode, state: code.value } })
      .then(async (res: any) => {
        if (res.status.code === 200 && res.data.length > 0) {
          const index = handleAdd(specCode);
          currentSpec = res.data;
          if (res.data.length > 0) {
            let codeList = res.data.map((m: any) => m.feeCode);
            const feeCodeList = codeList.join(',');
            findFeeCodeExtenFieldsValueList(feeCodeList);
          }
          specSignDetailList[index].id = res.data[0].id;
          specSignDetailList[index].reqNo = res.data[0].reqNo;
          Object.assign(specSignDetailList[index], res.data[0]);
          if (res.data[0].isSign === 1) {
            //已经签收的做提示
            specCodeInputBlur();
            let content = '当前标本';
            //content += res.isSigned ? `已于${res.data[0].signTime}${res.data[0].signerNa ? '被' + res.data[0].signerNa + '操作' : ''}接收` : '';
            content += `已于${res.data[0].signTime}${res.data[0].signerNa ? '被' + res.data[0].signerNa + '操作' : ''}接收`;
            content += ',请先退回才能再次接收';
            const type = await VXETable.modal.confirm(content);
            clearCurrentSpecsamplingDetail();
            currentSpec = {};
            specSignDetailList.splice(index, 1);
            const time = setTimeout(() => {
              clearSpecCodeInput();
              clearTimeout(time);
            }, 200);
          } else {
            specCodeInputEnter(res.data[0].id, res.data[0].reqNo, index);
          }
        } else {
          await VXETable.modal.alert(res.status.msg);
          //const type = await VXETable.modal.confirm(res.status.msg);

          const time = setTimeout(() => {
            clearSpecCodeInput();
            clearTimeout(time);
          }, 200);
          //VxeMessage(res.status.msg, VxeNotifyType.error);

        }

        // if (res.status.code === 200 && (res.data.length > 0)) {
        //   currentSpec = res.data;
        //   specSamplingDetailList[index].id = res.data[0].id;
        //   specSamplingDetailList[index].reqNo = res.data[0].reqNo;
        //   Object.assign(specSamplingDetailList[index], res.data[0]);
        //   if (res.data[0].isSign || res.data[0].isSampling) {
        //     specCodeInputBlur();
        //     let content = '当前标本';
        //     content += res.data[0].isSign ? `已于${res.data[0].signTime}${res.data[0].signerNa ? '被' + res.data[0].signerNa + '操作' : ''}签收\n` : '';
        //     content += res.data[0].isSampling ? `已于${res.data[0].samplingTime}${res.data[0].samplingDoctorNa ? '被' + res.data[0].samplingDoctorNa + '操作' : ''}采集` : '';
        //     content += ',需要再次采集吗？';
        //     const type = await VXETable.modal.confirm(content);
        //     if (type === 'confirm') {
        //       specCodeInputEnter(res.data[0].id, res.data[0].reqNo, index);
        //     } else if (type === 'cancel') {
        //       currentSpec = {};
        //       clearCurrentSpecsamplingDetail();
        //       specSamplingDetailList.splice(index, 1);
        //       const time = setTimeout(() => {
        //         clearSpecCodeInput();
        //         clearTimeout(time);
        //       }, 200);
        //     }

        //   } else {
        //     specCodeInputEnter(res.data[0].id, res.data[0].reqNo, index);
        //   }
        // }
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  } catch (err) {
    // clearSpecCodeInput();
    specCodeInputBlur();
    proxy.$alert(err.data.error.message, '提示', {
      callback: (action) => {
        const time = setTimeout(() => {
          clearSpecCodeInput();
          clearTimeout(time);
        }, 200);
      }
    });
  }
}

function findFeeCodeExtenFieldsValueList(data: any) {

  const url = '/lis/fee/item/findFeeCodeExtenFieldsValueList';
  proxy.$http
    .get(url, {
      params: {
        moduleId: '1716657789982969857',
        menuId: '1734129954829893633',
        tabKey: '001',
        busRowId: data
      }
    })
    .then((res: any) => {
      if (res.data.length > 0) {
        res.data.forEach((item: any) => {
          formData[item.feeCode] = item.value;
        });
      }
      console.log('formData', formData)
    })
}

// 清屏
// function ClearScreen() {
//   specSignDetailList.length = 0;
//   return;
// }
//页签选择改变
function tabSelectChange(e) {
  // console.log('页签', e);
}
//创建标本接收
// function saveSpecSign(index) {
//   const url = '/api/lims/spec-signs';
//   const data = {
//     // tenantId: EmptyUUID(),
//     organizationUnitId: userInfo.employee ? userInfo.employee.organizationUnitId : null,
//     specSignNo: '',
//     signerId: userInfo.employeeId,
//     signTime: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
//     specialConsiderations: ''
//   };
//   return new Promise((resolve, reject) => {
//     axios
//       .post(url, data)
//       .then((res: any) => {
//         currentSpecSign = res;
//         resolve({ state: true, data: res });
//       })
//       .catch((err) => {
//         errData = err;
//         reject({ state: false });
//         // 报错后显示重新接收
//         specSignDetailList[index].isAgain = true;
//         (proxy.$refs.specSignDetailTable as any).reloadData(specSignDetailList);
//         proxy.$alert(err.data.error.message, '提示');
//       });
//   });
// }
//创建标本接收详情
// function saveSpecSignDetail(specId, specSign, index) {
//   const url = '/api/lims/spec-sign-details';
//   const data = {
//     specSignId: specSign.id,
//     specId,
//     specialConsiderations: ''
//   };
//   axios
//     .post(url, data)
//     .then((res: any) => {
//       res.isSuccess = true;
//       res.loading = false;
//       currentSpecSignDetail = res;
//       if (!IsEmpty(index)) {
//         specSignDetailList[index] = Object.assign({}, res);
//       }

//       (proxy.$refs.specSignDetailTable as any).reloadData(specSignDetailList);
//     })
//     .catch((err) => {
//       // 报错后显示重新接收
//       specSignDetailList[index].isAgain = true;
//       (proxy.$refs.specSignDetailTable as any).reloadData(specSignDetailList);
//       $alert(err.data.error.message, '提示');
//     });
// }
// 批量接收
// async function handleSign() {
//   if (newSpecSignDetailList.length === 0) {
//     (this as any).$XModal.message({ content: '没有可以接收的标本', status: 'error' });
//     return;
//   }
//   for (let i = 0; i < newSpecSignDetailList.length; i++) {
//     const item = newSpecSignDetailList[i];
//     newSpecSignDetailList[i].isAgain = false;
//     newSpecSignDetailList[i].loading = true;
//     const specSign: any = await saveSpecSign(item.index);
//     if (specSign.state) {
//       saveSpecSignDetail(item.specId, specSign.data, item.index);
//     }
//     if (i === newSpecSignDetailList.length - 1) {
//       newSpecSignDetailList = [];
//     }
//   }
// }
// 重新接收
function againSign(row, rowIndex) {
  if (row.specId) {
    specCodeInputEnter(row.id, row.reqNo, rowIndex);
  } else {
    getspecByCode(row.reqNo);
  }
}

//右键菜单
function contextMenuClickEventTop({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      if (row && column) {
        const a = 'spec';
        if (XEClipboard.copy(row[a][column.property])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    default:
      VXETable.modal.message(`点击了 ${menu.name} 选项`);
  }
}
let returnReasonModule = ref(false);
let returnReason = '';
//  标本退回
function returnSpec() {
  if (IsEmpty(currentSpecSignDetail.reqNo) || IsEmpty(currentSpecSignDetail.id)) {
    //(this as any).$XModal.message({ content: '请先选择回退标本', status: 'warning' });
    VxeMessage('请先选择回退标本', VxeNotifyType.error);
    return;
  } else {
    returnReasonModule.value = true;
  }
}
let currentRow = reactive({});
function confirmReturnSpec() {
  if (unqualifiedDetailIds.length == 0 || IsEmpty(unqualifiedDetailIds)) {
    VxeMessage('请选择回退原因', VxeNotifyType.error);
    return;
  }
  loading.value = true;
  //当前登录用户 EmpId
  const url = '/lab/req/unqualified/detail/saveDetail';
  const data = {
    reqNo: currentRow.reqNo,
    unqualifiedDetailIds: unqualifiedDetailIds
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage('操作成功', VxeNotifyType.success);
        returnReasonModule.value = false;
        loading.value = false;
        const index = (proxy.$refs.specSignDetailTable as any).getRowIndex(currentSpecSignDetail);
        specSignDetailList.splice(index, 1);
      } else {
        loading.value = false;
        VxeMessage('操作失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('操作失败', VxeNotifyType.error);
    });
}

function selectAll() {
  proxy.$nextTick(() => {
    // proxy.$refs.inputRef.focus();
    proxy.$refs.specCodeInput.select();
  });
}

// #endRegion
</script>
<style lang="scss" scoped>
#specCollection {
  height: 100%;

  .bodyContent {
    height: calc(100% - 20px);

    .el-tabs {
      height: 100%;
      background-color: $base-white;

      :deep(.el-tabs__content) {
        height: calc(100% - 39px - 10px);
        padding: 5px;

        .el-tab-pane {
          height: 100%;

          .button-blue,
          .button-red {
            margin: 5px 0 5px 5px;
          }
        }
      }
    }
  }

  .specSignDetailTable {
    height: calc(100vh - 40px - 82px - 5px);
  }
}
</style>
